package com.zhangsun.yueBoot.framework.handler;

import com.alibaba.fastjson.JSON;
import com.zhangsun.yueBoot.commons.base.bean.ResponseResult;
import com.zhangsun.yueBoot.commons.logger.MyLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 无权限访问处理
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private MyLoggerFactory logger;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 登陆状态下，权限不足执行该方法
        logger.error("权限不足：" + e.getMessage());
        logger.error(e);
        httpServletResponse.setStatus(403);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        ResponseResult responseResult = ResponseResult.error("403", "无权限访问该接口");
        printWriter.write(JSON.toJSONString(responseResult));
        printWriter.flush();
    }

}
